using Microsoft.Extensions.Logging;

namespace Traceability.API.Services
{
    /// <summary>
    /// 混合验证码服务（优先Redis，备用内存）
    /// </summary>
    public class HybridCaptchaService
    {
        private readonly RedisCaptchaService _redisCaptchaService;
        private readonly MemoryCaptchaService _memoryCaptchaService;
        private readonly ILogger<HybridCaptchaService> _logger;
        private bool _redisAvailable = true;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="redisCaptchaService">Redis验证码服务</param>
        /// <param name="memoryCaptchaService">内存验证码服务</param>
        /// <param name="logger">日志记录器</param>
        public HybridCaptchaService(
            RedisCaptchaService redisCaptchaService, 
            MemoryCaptchaService memoryCaptchaService,
            ILogger<HybridCaptchaService> logger)
        {
            _redisCaptchaService = redisCaptchaService;
            _memoryCaptchaService = memoryCaptchaService;
            _logger = logger;
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="length">验证码长度</param>
        /// <param name="width">图片宽度</param>
        /// <param name="height">图片高度</param>
        /// <param name="expireSeconds">过期时间（秒）</param>
        /// <returns>验证码信息（ID、图片、过期时间）</returns>
        public async Task<(string CaptchaId, byte[] ImageBytes, DateTime ExpireTime)> GenerateCaptchaAsync(
            int length = 4, 
            int width = 120, 
            int height = 40, 
            int expireSeconds = 300)
        {
            // 优先尝试Redis
            if (_redisAvailable)
            {
                try
                {
                    var result = await _redisCaptchaService.GenerateCaptchaAsync(length, width, height, expireSeconds);
                    _logger.LogInformation("验证码生成成功 - 使用Redis存储");
                    return result;
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "Redis验证码服务失败，切换到内存存储");
                    _redisAvailable = false;
                }
            }

            // 使用内存备用方案
            try
            {
                var result = await _memoryCaptchaService.GenerateCaptchaAsync(length, width, height, expireSeconds);
                _logger.LogInformation("验证码生成成功 - 使用内存存储");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "内存验证码服务也失败了");
                throw new Exception("验证码服务不可用", ex);
            }
        }

        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="captchaId">验证码ID</param>
        /// <param name="inputCode">用户输入的验证码</param>
        /// <returns>验证结果</returns>
        public async Task<bool> ValidateCaptchaAsync(string captchaId, string inputCode)
        {
            // 优先尝试Redis
            if (_redisAvailable)
            {
                try
                {
                    bool redisResult = await _redisCaptchaService.ValidateCaptchaAsync(captchaId, inputCode);
                    _logger.LogInformation("验证码验证完成 - 使用Redis存储，结果: {Result}", redisResult);
                    return redisResult;
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "Redis验证码验证失败，尝试内存存储");
                    _redisAvailable = false;
                }
            }

            // 使用内存备用方案
            try
            {
                bool memoryResult = await _memoryCaptchaService.ValidateCaptchaAsync(captchaId, inputCode);
                _logger.LogInformation("验证码验证完成 - 使用内存存储，结果: {Result}", memoryResult);
                return memoryResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "内存验证码验证也失败了");
                return false;
            }
        }

        /// <summary>
        /// 检查Redis连接状态并尝试恢复
        /// </summary>
        public async Task<bool> CheckRedisHealthAsync()
        {
            try
            {
                // 尝试生成一个测试验证码来检查Redis连接
                await _redisCaptchaService.GenerateCaptchaAsync(4, 120, 40, 60);
                _redisAvailable = true;
                _logger.LogInformation("Redis连接恢复正常");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "Redis连接仍然不可用");
                _redisAvailable = false;
                return false;
            }
        }

        /// <summary>
        /// 获取当前使用的存储类型
        /// </summary>
        /// <returns>存储类型</returns>
        public string GetCurrentStorageType()
        {
            return _redisAvailable ? "Redis" : "Memory";
        }
    }
}
